﻿/*
 * @author Lee 
 * Time: 20180403 
 * Abstract: SharePoint API的二次封装
 */

using System;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Security.Cryptography;
using System.Globalization;

namespace SharePointHelper.DLL.SSOM
{
	public class Analytics
	{
		/// <summary>
		/// 为SharePoint object计算MD5值
		/// http://otak-otak-it.blogspot.com/2011/05/how-to-get-sharepoint-2010-web.html
		/// </summary>
		internal static class CommonMethods
		{
			internal static class Hasher
			{
				internal static byte[] ComputeHash(string input)
				{
					if (string.IsNullOrEmpty(input))
						return null;
					return MD5.Create().ComputeHash(Encoding.Unicode.GetBytes(input));
				}

				internal static string ConvertHashToString(byte[] hash)
				{
					if (hash == null)
						return null;
					StringBuilder builder = new StringBuilder("0x");
					for (int i = 0; i < hash.Length; i++)
					{
						builder.Append(hash[i].ToString("X2", CultureInfo.InvariantCulture));
					}
					return builder.ToString();
				}
			}
		}

		/// <summary>
		/// 获取聚合 id (for SharePoint anayltics reports)
		/// http://otak-otak-it.blogspot.com/2011/05/how-to-get-sharepoint-2010-web.html
		/// </summary>
		public static class AggregationIdGenerator
		{
			private static Guid GetAggregationId(string id)
			{
				return new Guid(CommonMethods.Hasher.ComputeHash(id));
			}

			public static Guid GetAggregationIdForFarm()
			{
				return GetAggregationId(GetFarmId().ToString());
			}

			public static Guid GetAggregationIdForFarm(Guid farmId)
			{
				if (farmId == Guid.Empty)
					return Guid.Empty;
				return GetAggregationId(farmId.ToString());
			}

			public static Guid GetAggregationIdForServiceApplication(SPServiceApplication serviceApplication)
			{
				if (serviceApplication == null)
					throw new ArgumentNullException("serviceApplication");
				return GetAggregationId(serviceApplication.Id.ToString());
			}

			public static Guid GetAggregationIdForServiceApplication(Guid serviceApplicationId)
			{
				if (serviceApplicationId == Guid.Empty)
					return Guid.Empty;
				return GetAggregationId(serviceApplicationId.ToString());
			}

			public static Guid GetAggregationIdForSite(SPSite site)
			{
				if (site == null)
					throw new ArgumentNullException("site");
				return GetAggregationId(site.ID.ToString());
			}

			public static Guid GetAggregationIdForSite(Guid siteId)
			{
				if (siteId == Guid.Empty)
					return Guid.Empty;
				return GetAggregationId(siteId.ToString());
			}

			public static Guid GetAggregationIdForWeb(SPWeb web)
			{
				if (web == null)
					throw new ArgumentNullException("web");
				return GetAggregationId(web.Site.ID.ToString() + web.ID.ToString());
			}

			public static Guid GetAggregationIdForWeb(string webUrl)
			{
				if (webUrl == null)
					throw new ArgumentNullException("webUrl");
				using (SPSite site = new SPSite(webUrl))
				{
					if (site != null)
						using (SPWeb web = site.OpenWeb())
						{
							if (web != null)
								return GetAggregationId(site.ID.ToString() + web.ID.ToString());
						}
				}
				return Guid.Empty;
			}

			public static Guid GetAggregationIdForWeb(Guid siteId, Guid webId)
			{
				if (siteId == Guid.Empty)
					return Guid.Empty;
				if (webId == Guid.Empty)
					return Guid.Empty;
				return GetAggregationId(siteId.ToString() + webId.ToString());
			}

			public static Guid GetAggregationIdForWebApplication(SPWebApplication webApplication)
			{
				if (webApplication == null)
					throw new ArgumentNullException("webApplication");
				return GetAggregationId(webApplication.Id.ToString());
			}

			public static Guid GetAggregationIdForWebApplication(Guid webApplicationId)
			{
				if (webApplicationId == Guid.Empty)
					return Guid.Empty;
				return GetAggregationId(webApplicationId.ToString());
			}

			private static Guid GetFarmId()
			{
				SPFarm local = SPFarm.Local;
				if (local == null)
					throw new InvalidOperationException("Server not joined in farm: " + System.Net.Dns.GetHostName());
				return local.Id;
			}
		}


		public static DataTable GetMostPopular(string assetGuid, DateTime startDate, DateTime endDate, int maxRows)
		{
			DataTable dt = null;
			try
			{
				// 初始化

				// sql query

			}
			catch (Exception ex)
			{
				Log.WriteError("4567yrrdsgrsdsre", ex);
				dt = null;
			}
			return dt;
		}
	}

	/// <summary>
	/// Google Analytics 
	/// </summary>
	public class GoogleAnalytics
	{
		public class Email
		{
            /// <summary>
            /// 格式通过的URL，附加谷歌分析参数跟踪电子邮件用户的类型，点击电子邮件，和用户名
            /// 也将追加 utm_medium=email parameter
            /// http://cutroni.com/blog/2008/11/04/email-tracking-with-google-analytics/
            /// </summary>
            /// <param name="originalUrl"></param>
            /// <param name="campaign">the email type</param>
            /// <param name="username">username to track, will be encoded for you</param>
            /// <returns></returns>
            public static string FormatUrl(string originalUrl, string campaign, string username)
			{
				string url = originalUrl;
				try
				{
					if (!string.IsNullOrEmpty(url))
					{
						// add medium
						url = Utilities.AppendUrlParameter(url, "utm_medium", "email", false);

						// add campaign
						if (!string.IsNullOrEmpty(campaign))
						{
							url = Utilities.AppendUrlParameter(url, "utm_campaign", campaign, true);
						}
						
						// add source
						if (!string.IsNullOrEmpty(username))
						{
							if (username.Contains("|")) { username = Security.FormatUsername(username); }
							url = Utilities.AppendUrlParameter(url, "utm_source", username, true);
						}
					}
				}
				catch (Exception ex)
				{
					Log.WriteError("8ityu6rerdsfdsf", ex, "original url: " + originalUrl + ", formatted url: " + url);
					url = originalUrl;
				}
				return url;
			}

            /// <summary>
            /// 输出信标html，放置在电子邮件的底部。
            /// google campaign parameters不会出现在里面
            /// </summary>
            /// <param name="imageUrl"></param>
            /// <param name="campaign"></param>
            /// <param name="username"></param>
            /// <returns></returns>
            public static string BeaconImage(string imageUrl, string campaign, string username)
			{
				return "<img src=\"" + FormatUrl(imageUrl, campaign, username) + "\" width=\"1px\" height=\"1px\" />";
			}
		}
	}
}
